package com.frog.framework.dynamo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;

import java.net.URI;

/**
 * @author wuqiong 2022/3/3
 * @description
 */
@Configuration
public class FrogDynamoDbClient {
    private static final Logger logger = LoggerFactory.getLogger(FrogDynamoDbClient.class);

    @Value("${frog.dynamoDb.accessKeyId:}")
    private String dynamoDbAccessKeyId;
    @Value("${frog.dynamoDb.secretAccessKey:}")
    private String dynamoDbSecretAccessKey;
    @Value("${frog.dynamoDb.region:us-east-2}")
    private String dynamoDbRegion;
    @Value("${frog.dynamoDb.endpoint:}")
    private String endpoint;

    // DynamoDb  连接
    private volatile static DynamoDbClient dynamoDbClient;


    /**
     * 获取 原始 dynamo db 连接
     *
     * @return DynamoDbClient
     * @author wuqiong 2022/7/21 15:13
     */
    @Bean
    public DynamoDbClient registerDynamoDBClient() {
        return getDynamoDbClient();
    }

    /**
     * 获取 增强的 dynamo db 连接
     *
     * <pre>
     *     使用案例:
     *     // user_dynamic_message 为 dynamoDB的表名
     *     DynamoDbTable<UserDynamicMessage> dynamicMessage =
     *             enhancedClient.table("user_dynamic_message", TableSchema.fromBean(UserDynamicMessage.class));
     *
     *     // 170873 为 数据主键
     *     Key key = Key.builder().partitionValue("170873").build();
     *     // 获取主键所对应的数据
     *     UserDynamicMessage messageItem = dynamicMessage.getItem(key);
     *
     * </pre>
     *
     * @return DynamoDbEnhancedClient
     * @author wuqiong 2022/7/21 18:44
     */
    @Bean
    public DynamoDbEnhancedClient registerDynamoDbEnhancedClient() {
        return DynamoDbEnhancedClient.builder()
                .dynamoDbClient(getDynamoDbClient())
                .build();
    }

    /**
     * 获取 dynamo db 连接
     *
     * @return DynamoDbClient
     * @author wuqiong 2022/7/21 15:13
     */
    private DynamoDbClient getDynamoDbClient() {
        if (dynamoDbClient != null) return dynamoDbClient;
        synchronized (DynamoDbClient.class) {
            if (dynamoDbClient != null) return dynamoDbClient;
            // 如果从配置信息未读取到key和secret 信息则从环境变量里面取，如果还没有取到,则让程序去主目录下的 .aws/credentials 寻找
            if (dynamoDbAccessKeyId == null || dynamoDbAccessKeyId.trim().length() == 0 ||
                    dynamoDbSecretAccessKey == null || dynamoDbSecretAccessKey.trim().length() == 0) {
                logger.warn("[DynamoDb Client] 从配置文件内未找到配置数据,所以准备在环境变量内查找");
                String envAccessKeyId = System.getenv("accessKeyId");
                String envSecretAccessKey = System.getenv("secretAccessKey");
                String envRegion = System.getenv("region");
                if (envAccessKeyId == null || envAccessKeyId.trim().length() == 0 ||
                        envSecretAccessKey == null || envSecretAccessKey.trim().length() == 0) {
                    logger.warn("[DynamoDb Client] 默认没有找到环境变量的数据，因此去主目录下的 .aws/credentials 寻找");
                    // 此时环境变量内没有注入,此时采用自加载模式,会去主目录下的 .aws/credentials 寻找
                    dynamoDbClient = DynamoDbClient.builder().region(Region.of(dynamoDbRegion)).build();
                    return dynamoDbClient;
                }
                dynamoDbAccessKeyId = envAccessKeyId;
                dynamoDbSecretAccessKey = envSecretAccessKey;
                dynamoDbRegion = envRegion != null && envRegion.trim().length() > 0 ? envRegion : dynamoDbRegion;
            }
            dynamoDbClient = DynamoDbClient.builder()
                    .endpointOverride(URI.create(endpoint))
                    .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(dynamoDbAccessKeyId, dynamoDbSecretAccessKey)))
                    .region(Region.of(dynamoDbRegion))
                    .build();
            return dynamoDbClient;
        }
    }


}
